<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="姓名" prop="workerName">
        <el-input
          v-model="queryParams.workerName"
          placeholder="请输入员工姓名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="身份证" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入员工身份证"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="黑名单" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in hmdOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          :loading="exportLoading"-->
<!--          @click="handleExport"-->
<!--        >导出-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partTimeJobs" >

      <el-table-column label="员工编号" prop="id" width="80"/>
      <el-table-column label="员工姓名" prop="workerName" :show-overflow-tooltip="true" width="100"/>
      <el-table-column label="性别" align="center" prop="sex" width="80">
        <template slot-scope="scope">
          <div v-if="scope.row.sex == 1">男</div>
          <div v-else-if="scope.row.sex == 2">女</div>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phoneCode" min-width="100"/>
      <el-table-column label="身份证" align="center" prop="idCard" min-width="100"/>
      <el-table-column label="银行卡号" align="center" prop="bankCardNumber" min-width="200"/>
      <el-table-column label="银行开户行" align="center" prop="bankAddress" min-width="60" show-overflow-tooltip/>
      <el-table-column label="黑名单" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.$index,scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  min-width="120" class-name="small-padding">
        <template slot-scope="scope" >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['job:worker:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
            v-hasPermi="['job:worker:delete']"
          >删除</el-button>
          <el-button
            v-if="scope.row.mediaFileId !=0"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handOpenImage(scope.row)"
            v-hasPermi="['job:worker:idcard']"
          >身份证链接</el-button>

        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div class="block">
        <span class="demonstration">身份证正面照片</span>
        <el-image :src="imgSrc"></el-image>
      </div>
      <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
            </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="yhk"
      width="30%"
    >
      <div class="block">
        <span class="demonstration">银行卡照片</span>
        <el-image :src="imgSrc"></el-image>
      </div>
      <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="yhk = false">关 闭</el-button>
            </span>
    </el-dialog>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="workerName">
              <el-input v-model="form.workerName" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="form.idCard"  placeholder="请输入身份证"  maxlength="32"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phoneCode">
              <el-input v-model="form.phoneCode" placeholder="请输入联系方式" maxlength="11" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="银行卡号" prop="bankCardNumber">
              <el-input v-model="form.bankCardNumber" placeholder="请输入银行卡号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户行地址" prop="bankAddress">
              <el-input v-model="form.bankAddress"  placeholder="请输入开户行地址"  maxlength="32"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  拉黑表单  -->
    <el-dialog :title="block_worker.title" :visible.sync="block_worker.open" width="400px" append-to-body>
      <el-form ref="block_worker_data" :model="block_worker.data" label-width="80px">
        <el-form-item label="拉黑原因">
          <el-input type="textarea" v-model="block_worker.data.blockRemark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit_block_worker_data">确 定</el-button>
        <el-button @click="block_worker.open = false">取 消</el-button>
      </div>
    </el-dialog>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  listWorkerlist,
  modifyWorkerInfo,
  getWorker,
  changeWorkerStatus,
  getImg,
  delWorker,
  addBlock,
  removeFromBlock
} from "@/api/partTimeJob/workerInfo/workerInfo";

export default {
  name: "worker",
  data() {
    return {
      sexOptions:[{value: 1, label: '男'}, {value: 2, label: '女'}],
      dialogVisible:false,
      yhk:false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      partTimeJobs: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 黑名单下拉
      statusOptions: [{value: 1, label: '是'}, {value: 2, label: '否'}],
      //拉黑项
      block_worker:{
        data:{},
        title:'拉黑表单提交',
        open:false,
      },
      workStatusOptions: [{value: 1, label: '已报名'}, {value: 2, label: '已签到'}, {value: 3, label: '候选'}, {
        value: 4,
        label: '已取消候选'
      }, {value: 5, label: '已取消报名'}, {value: 6, label: '已完成'}],
      //用人单位下拉
      companyOptions: [],
      //班次下拉
      timShiftOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        //员工姓名
        workerName: undefined,
      },
      imgSrc:'',
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        workerName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '姓名长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: "身份证不能为空", trigger: "blur" }
        ],

        sex: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        bankCardNumber: [
          { required: true, message: "银行卡不能为空", trigger: "blur" }
        ],
        bankAddress: [
          { required: true, message: "开户行地址不能为空", trigger: "blur" }
        ],
        phoneCode: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      hmdOptions:[{value: 1, label: '否'}, {value: 0, label: '是'}],
    };
  },
  created() {
    this.getTime();
    this.getList();

  },
  watch: {
    //监听拉黑名单是否关闭
    'block_worker.open':{
      handler(newVal, oldVal) {
        let index = this.block_worker.index;
        console.log('obj.a changed',newVal,oldVal,index);
        if (!this.block_worker.submit&&oldVal){
          let job = this.partTimeJobs[index];
          job.status = (job.status === 1 ? 0 : 1);
          console.log("是否提交:",this.block_worker.submit,job);
        }
      },
      // immediate: true,
    }
  },
  methods: {
    getTime() {
      let _this = this;
      let date = new Date();
      let y = date.getFullYear();
      let m = (date.getMonth() + 1) < 10 ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1);
      let d = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();

      let start_month = y + '-' + '01';   //开始月份：本年第一月份
      let end_month = `${y}-${m}`;        //结束月份： 本年当前月份

      let start_day = `${y}-${m}-${d}`;       //开始日期： 本月第一天
      let end_day = `${y}-${m}-${d}`;     //结束日期： 本月今天

      //_this.aa = [start_month, end_month];   //默认月份区间
      _this.dateRange = [start_day, end_day];        //默认日期区间

    },
    /** 获取员工信息列表 */
    getList() {
      this.loading = true;
      listWorkerlist(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.partTimeJobs = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    //黑名单
    handleStatusChange(index,row) {
      let text = row.status === 0 ? "加入黑名单" : "移除黑名单";
      if (row.status === 0){
        this.block_worker = {
          data:row,
          open:true,
          title:text,
          submit:false,
          index:index,
        };
      }else {
        this.remove_block_list(row,text);
      }
      /*
      let text = row.status == "0" ? "停用" : "启用";
      this.$confirm('确认要"' + text + '""' + row.workerName + '"吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeWorkerStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });

      */
    },
    //移除黑名单
    remove_block_list(row, text) {
      console.log("row",row);
      this.$confirm('确认要将' + row.workerName + text + '吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return removeFromBlock(
          {
            workerId: row.id,
            workerType: 2
          }
        );
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(action => {
        // console.log("action",action,"row.status:",row.status,row.status === 1)
        action === 'cancel'||'close' ? (row.status = row.status === 1 ? 0 : 1) : '';
      });
    },
    //提交表单
    submit_block_worker_data(){
      let data = this.block_worker.data;
      let form = {
        workerId:data.id,
        workerName:data.workerName,
        idCard:data.idCard,
        phoneCode:data.phoneCode,
        blockRemark:data.blockRemark,
      }
      console.log(this.block_worker);
      this.$confirm('是否确认提交？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return addBlock(form);
      }).then((res) => {
        if (res.code === 200){
          this.block_worker.open = false;
          this.block_worker.submit=true
          this.getList();
          this.msgSuccess("加入黑名单成功");
        }
      }).catch(() => {
      });
    },

    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          //员工姓名
          workerName: undefined,
          //身份证
          idCard: undefined,
          //银行卡
          bankCardNumber: undefined,
          //黑名单
          //手机号码
          phoneCode: undefined,
          //供应商
          company: undefined,
          //班次
          timShiftTYpe: undefined,
          companyId: undefined,
          timeShiftType: undefined,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },


    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有员工数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportWorkerInfos(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWorker(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },


    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            modifyWorkerInfo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleUpdateWork(param) {
      let workStatus = param.workStatus == 1 ? '签到' : param.workStatus == 2 ? '签退' : '';
      let text = param.workerName
      let status = param.workStatus == 1 ? 2 : param.workStatus == 2 ? 6 : 0;
      changeWorkStatus(param.orderCode, status).then(res => {
        this.msgSuccess(text + workStatus + "成功");
      }).catch(() => {
        this.msgError(text + workStatus + "失败");
      })
    },
    handOpenImage(row) {
      this.dialogVisible = true
      getImg(row.id).then(res => {
        this.imgSrc = res.data;
      })
    },
    /** 删除按钮操作 */
    handleDel (row) {
      const id = row.id;
      this.$confirm('是否确认删除姓名为"' + row.workerName  + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delWorker(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
  },
};
</script>
